﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace Hsp.Auto.Common.Utility
{
    /// <summary>
    ///     文件帮助类
    /// </summary>
    public class FileHelper
    {
        #region 将 Stream 转成 byte[]

        /// <summary>
        ///     将 Stream 转成 byte[]
        /// </summary>
        public static byte[] StreamToBytes(Stream stream)
        {
            var bytes = new byte[stream.Length];
            stream.Read(bytes, 0, bytes.Length);

            // 设置当前流的位置为流的开始 
            stream.Seek(0, SeekOrigin.Begin);
            return bytes;
        }

        #endregion

        #region 如果目录不存在，建立

        /// <summary>
        /// 如果目录不存在，建立
        /// </summary>
        /// <param name="dirName">目录名称</param>
        public static void FilePathCheck(string dirName)
        {
            var directoryName = Path.GetDirectoryName(dirName);
            if (directoryName == null) return;
            String path = directoryName.TrimEnd('\\');
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
        }

        #endregion


        #region 为文件名补充程序集所在路径

        /// <summary>
        ///     为文件名补充程序集所在路径。
        /// </summary>
        /// <param name="FileName">文件名</param>
        /// <returns>带路径名的文件名</returns>
        public static string GetFilePath(string FileName)
        {
            if (!Path.IsPathRooted(FileName))
            {
                FileName = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, FileName);
            }
            FileName = Path.GetFullPath(FileName);
            return FileName;
        }

        #endregion

        #region 用时间和随机数产生文件名

        /// <summary>
        ///     用时间和随机数产生文件名
        /// </summary>
        /// <returns></returns>
        public static string GenerateFileName()
        {
            DateTime dtTemp = DateTime.Now;
            string sTemp = FormatDateTimeToURLString(dtTemp);
            var rand = new Random(unchecked((int)DateTime.Now.Ticks));
            string sRand = rand.Next(0, 99999).ToString("0####");
            return sTemp + sRand;
        }

        public static string GenerateFileName(string UserID)
        {
            DateTime dtTemp = DateTime.Now;
            string sTemp = FormatDateTimeToURLString(dtTemp);
            var rand = new Random(unchecked((int)DateTime.Now.Ticks));
            string sRand = rand.Next(0, 99999).ToString("0####");
            return sTemp + "-" + UserID + "-" + sRand;
        }

        public static string GenerateFileName(Random pRand)
        {
            DateTime dtTemp = DateTime.Now;
            string sTemp = FormatDateTimeToURLString(dtTemp);
            string sRand = pRand.Next(0, 99999).ToString("0####");
            return sTemp + sRand;
        }

        public static string GenerateFileName(Guid id)
        {
            DateTime dtTemp = DateTime.Now;
            string sTemp = FormatDateToURLString(dtTemp);
            var rand = new Random(unchecked((int)DateTime.Now.Ticks));
            string sRand = rand.Next(0, 99999).ToString("0###");
            return String.Format("{0}{1}{2}", sTemp, id.ToString().Replace("-", "").ToUpper(), sRand);
        }

        /// <summary>
        ///     将日期类型转成yyyyMMdd
        /// </summary>
        /// <param name="argDt"></param>
        /// <returns></returns>
        public static string FormatDateToURLString(DateTime argDt)
        {
            string strDate = FormatDateToString(argDt).Replace("-", "");
            return strDate;
        }

        /// <summary>
        ///     将日期类型转成yyyy-MM-dd
        /// </summary>
        /// <param name="argDt"></param>
        /// <returns></returns>
        public static string FormatDateToString(DateTime argDt)
        {
            string strYear = argDt.Year.ToString();
            string strMonth = argDt.Month.ToString();
            if (strMonth.Length == 1)
            {
                strMonth = "0" + strMonth;
            }
            string strDay = argDt.Day.ToString();
            if (strDay.Length == 1)
            {
                strDay = "0" + strDay;
            }
            return strYear + "-" + strMonth + "-" + strDay;
        }

        /// <summary>
        ///     将日期类型转成yyyyMMddhhmmss
        /// </summary>
        /// <param name="argDt"></param>
        /// <returns></returns>
        public static string FormatDateTimeToURLString(DateTime argDt)
        {
            string strDate = FormatDateToString(argDt).Replace("-", "");
            string strTime = FormatTimeToString(argDt).Replace(":", "");
            return strDate + strTime;
        }

        /// <summary>
        ///     将日期类型转成hh:mm:ss
        /// </summary>
        /// <param name="argDt"></param>
        /// <returns></returns>
        public static string FormatTimeToString(DateTime argDt)
        {
            string strHour = argDt.Hour.ToString();
            if (strHour.Length == 1)
            {
                strHour = "0" + strHour;
            }
            string strMinute = argDt.Minute.ToString();
            if (strMinute.Length == 1)
            {
                strMinute = "0" + strMinute;
            }
            string strSecond = argDt.Second.ToString();
            if (strSecond.Length == 1)
            {
                strSecond = "0" + strSecond;
            }
            return strHour + ":" + strMinute + ":" + strSecond;
        }

        #endregion

        #region Files the content.

        /// <summary>
        ///     Files the content.
        /// </summary>
        /// <param name="fileName">Name of the file.</param>
        /// <returns></returns>
        public static Byte[] FileContent(string fileName)
        {
            var fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
            try
            {
                var buffur = new byte[fs.Length];
                fs.Read(buffur, 0, (int)fs.Length);
                return buffur;
            }
            catch (Exception ex)
            {
                //MessageBoxHelper.ShowPrompt(ex.Message);
                return null;
            }
            finally
            {
                //关闭资源
                fs.Close();
            }
        }

        #endregion

        #region 删除目录

        /// <summary>
        ///     删除目录
        /// </summary>
        /// <param name="dir"></param>
        /// <returns></returns>
        public string DeleteFolder(string dir)
        {
            if (Directory.Exists(dir)) //如果存在这个文件夹删除之 
            {
                foreach (string d in Directory.GetFileSystemEntries(dir))
                {
                    if (File.Exists(d))
                        File.Delete(d); //直接删除其中的文件 
                    else
                        DeleteFolder(d); //递归删除子文件夹 
                }
                Directory.Delete(dir); //删除已空文件夹 
                return dir + " 文件夹删除成功";
            }
            return dir + " 该文件夹不存在"; //如果文件夹不存在则提示 
        }

        #endregion

        #region 文件名非法字符过滤方法

        /// <summary>
        /// 非法字符列表
        /// </summary>
        private static readonly char[] InvalidFileNameChars =
        {
            '"',
            '<',
            '>',
            '|',
            '\0',
            '\u0001',
            '\u0002',
            '\u0003',
            '\u0004',
            '\u0005',
            '\u0006',
            '\a',
            '\b',
            '\t',
            '\n',
            '\v',
            '\f',
            '\r',
            '\u000e',
            '\u000f',
            '\u0010',
            '\u0011',
            '\u0012',
            '\u0013',
            '\u0014',
            '\u0015',
            '\u0016',
            '\u0017',
            '\u0018',
            '\u0019',
            '\u001a',
            '\u001b',
            '\u001c',
            '\u001d',
            '\u001e',
            '\u001f',
            ':',
            '*',
            '?',
            '\\',
            '/'
        };

        /// <summary>
        /// 文件名非法字符过滤方法
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public static string CleanInvalidFileName(string fileName)
        {
            fileName = fileName + "";
            fileName = InvalidFileNameChars.Aggregate(fileName, (current, c) => current.Replace(c + "", ""));
            if (fileName.Length <= 1) return fileName;
            if (fileName[0] != '.') return fileName;
            fileName = "dot" + fileName.TrimStart('.');
            return fileName;
        }

        #endregion
    }
}